//路由
const express = require('express');
const path = require('path');
const luYou = express.Router();
const shuJuKu = require(path.resolve('moKuai/shuJuKu.js'));
const WebSocket = require('ws');

let laiYuan = 'http://localhost:3000';
//fetch的credentials为'include'时候 "Access-Control-Allow-Origin"不能为"*"

//允许跨域
luYou.all("*", function(qingQiu, xiangYing, jieZhe) {
	xiangYing.header("Access-Control-Allow-Origin", laiYuan);
	xiangYing.header("Access-Control-Allow-Headers", "content-type");
	xiangYing.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
	xiangYing.header("Access-Control-Allow-Credentials", "true");
	if (qingQiu.method.toLowerCase() == 'options')
		xiangYing.send(200); //让options尝试请求快速结束
	else jieZhe();
});
//静态目录
luYou.use(express.static('she-ji/dist')); //express.static '/'默认 index.html

//websocket
const wss = new WebSocket.Server({
	port: 8080
});

let dateNow = new Date().getTime();
let jueSeHaoChi, jueSeHaoYiYong, tongBuWuTi;
let jiShaXinXi = '';

function chuShiHua() {
	jueSeHaoChi = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
	jueSeHaoYiYong = new Map();
	jiShaXinXi = '';
}
chuShiHua();


function guangBo() {
	let now = new Date().getTime();
	let shiChang = now - dateNow;
	if (shiChang > 24 * 60 * 60 * 1000) {
		chuShiHua();
		dateNow = now;
	};

	wss.clients.forEach(ws => {
		let xinXiArr = [...jueSeHaoYiYong.values()];
		ws.send(JSON.stringify({
			xinXiArr,
			jiShaXinXi,
			shiJian: now
		}))
	})

	jueSeHaoYiYong.forEach(value => {
		value.woBeiDaJi = [];
	})
	jiShaXinXi = '';
}

setInterval(guangBo, 1000 / 60);

wss.on('connection', ws => {
	if (jueSeHaoChi.length > 0) {

		let jueSeHao = jueSeHaoChi.shift();
		jueSeHaoYiYong.set(jueSeHao, {
			woBeiDaJi: []
		});

		ws.send(JSON.stringify({
			jueSeHao
		}));

		ws.jueSeHao = jueSeHao;

	} else {
		ws.send(JSON.stringify({
			jueSeHao: '房间已满'
		}));

		return;
	}

	ws.on('message', message => {

		message = JSON.parse(message);

		if (message.leiXing == 'jiShaXinXi') {
			jiShaXinXi = message.neiRong;
			return;
		}

		let jueSe = jueSeHaoYiYong.get(message.jueSeHao);
		jueSe.jueSeHao = message.jueSeHao;
		jueSe.weiZhi = message.weiZhi;
		jueSe.xuanZhuan = message.xuanZhuan;
		jueSe.niuZhuan = message.niuZhuan;
		jueSe.dongZuo = message.dongZuo;

		if (message.woDaJi) {
			let beiDaJi = jueSeHaoYiYong.get(message.woDaJi.jueSeHao);
			message.woDaJi.jueSeHao = message.jueSeHao; //打击者角色号
			beiDaJi.woBeiDaJi.push(message.woDaJi);
		}

	})

	ws.on('close', () => {

		jueSeHaoYiYong.forEach((h, i, a) => {
			if (i === ws.jueSeHao) {
				a.delete(i);
				jueSeHaoChi.push(i);
			}
		})

	})
})

module.exports = luYou;
